import {recognitionLicense} from "../../util/car.js";
// pages/user/car.js
function listCar(that){
  wx.request({
    method: "GET",
    url: getApp().data.servser + '/car/list',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': 'Bearer ' + wx.getStorageSync('token')
    },
    data: {
      openId: wx.getStorageSync('openid')
    },
    success: function (res) {
      that.setData({
        istrue: false,
        cars: res.data.data.cars
      })
    }
  })
}
exports.listCar = listCar
Page({

  /**
   * 页面的初始数据
   */
  data: {
    files: [],
    istrue: false,
    no: '',
    start: '',
    end: '',
    parkList: [],
    addressObj : {},
    statusArr: [{key:"空闲",value: "0"},{key:"使用中",value: "1"},{key:"预定中",value: "2"},{key:"不可用",value: "3"}],
    address: "",
    location: "",
    status: "",
    price: "",
    desc: "",
    myParkList: []
  },
  chooseStatus(event) {
    let index = event.detail.value;
    let status = this.data.statusArr[parseInt(index)].key
    this.setData({
      status
    })
  },
  uploadImage(event) {
    console.log(event);
  },
  chooseAddress(event) {
    let address = this.data.parkList[parseInt(event.detail.value)].address;

    this.setData({
      addressObj: this.data.parkList[parseInt(event.detail.value)],
      address
    })
  },
  bindTimeChange(event) {
    let { detail: { value }, target: { dataset :  { type }  } } = event;
    this.setData({
      [type]: value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getParks: function() {
    wx.request({
      method: "GET",
      url: getApp().data.servser + "/car/parkinglist",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success:(res)=> {
        this.setData({
          parkList: res.data
        })
      },
      fail:(err)=> {
        console.log(err)
      }
    })
  },
  uplaodFile(files) {
    console.log('upload files', files)
    // 文件上传的函数，返回一个promise
    return new Promise((resolve, reject) => {
        
    })
},
getAccessToken(base) {
  return new Promise((resolve,reject)=> {
    wx.mew.rpc.insurance.mini.getTokenToUpload().then(result=> {
      wx.mew.qiniu(base,(res)=> {
        resolve(res);
      }, (error) => {
        reject(error);
        }, {
            "region": result.region,
            "domain": result.domain, 
            "key": result.key,
            "uptoken": result.token,
        })
    })
  })
},
chooseImage: function (e) {
  var that = this;
  wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        const tempFilePath = res.tempFilePaths[0];
        that.getAccessToken(tempFilePath).then(res=> {
             console.log(res.imageURL)
             that.setData({
               files: [res.imageURL]
             })
        })
      }
  })
},
  onLoad: function (options) {
    var that = this;
    listCar(that)
    this.getParks()
  },
  delete: function (e) {
    let seqID = e.target.dataset.id;
    let that = this
    wx.showModal({
      title: '提示',
      content: '确认要删除吗',
      success (res) {
        if (res.confirm) {
          wx.request({
            method: "POST",
            url: getApp().data.servser + '/car/deletePark',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            data: {
              seqId: seqID
            },
            success: res => {
              that.getParkList();
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  getParkList: function() {
    let apiURL = getApp().data.servser + `/car/myParkList?page=1&limit=-1&openId=${wx.getStorageSync('openid')}`;
    wx.request({
      method: "GET",
      url: apiURL,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        this.setData({
          myParkList: res.data.data
        })
      }
    })
  },
  save: function () {
    let apiURL = getApp().data.servser + '/car/addPark';

    let temp = this.data.statusArr.find(item=> item.key == this.data.status);
    let status = temp ? temp.value : "";
    let data = {
      parkingId: this.data.addressObj.seqId,
      timeStart: this.data.start,
      timeEnd: this.data.end,
      location: this.data.location,
      status: status,
      price: this.data.price,
      memo: this.data.memo,
      "openId": wx.getStorageSync('openid'),
      carUrl: this.data.files[0]
    }
    let flag = true;
    Object.keys(data).forEach(key=> {
      if(!data[key]) {
        flag = false;
      }
    })
    if(!flag) {
      wx.showToast({
        icon: "none",
        title: '请输入完整参数',
        duration: 2000
      })
      return;
    }
    wx.request({
      method: "GET",
      url: apiURL,
      data: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: ()=> {
        this.getParkList();
        this.setData({
          istrue: false
        })
      }
    })
  },
  update: function (e) {
    console.log(e);
    this.setData({
      istrue: true,
      no: e.currentTarget.dataset.no,
      seqId: e.currentTarget.dataset.seqid
    })
  },
  add: function () {
    this.setData({
      istrue: true
    })
  },
  formInputChange(e) {
    let type = e.target.dataset.type;
    let value = e.detail.value;
    this.setData({
      [type] : value
    })
  },
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getParkList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})